import { reqLogin, reqUserinfo, reqLogOut } from '@/api/user'
import { defineStore } from 'pinia'
import type { loginForm } from '@/api/user/type'
import { SET_TOKEN, GET_TOKEN } from '@/utils/token'
import { constRoutes, asyncRoutes } from '@/router/routes'
import { ref } from 'vue'
import router from '@/router'
import { cloneDeep } from 'lodash'
const filterRoutes = (asyncRoutes: any, routes: any) => {
  return asyncRoutes.filter((item: any) => {
    if (routes.includes(item.name)) {
      if (item.children && item.children.length > 0) {
        item.children = filterRoutes(item.children, routes)
      }
      return true
    }
  })
}
export const useUserStore = defineStore('user', () => {
  const token = ref(GET_TOKEN()) || ref('')
  const Avatar = ref('')
  const username = ref('')
  const menuRoutes = ref<any>([])
  const buttons = ref<any>([])
  const userLogin = async (data: loginForm) => {
    const res = await reqLogin(data)
    if (res.code == 200) {
      token.value = res.data
      SET_TOKEN(res.data as string)
      return 'ok'
    } else {
      return Promise.reject(new Error(res.message))
    }
  }
  const getUserInfo = async () => {
    const res = await reqUserinfo()
    if (res.code == 200) {
      Avatar.value = res.data.avatar
      username.value = res.data.name
      buttons.value = res.data.buttons
      const userAsyncRoutes = filterRoutes(cloneDeep(asyncRoutes), res.data.routes)
      menuRoutes.value = [...constRoutes, ...userAsyncRoutes]
      userAsyncRoutes.forEach((item: any) => {
        router.addRoute(item)
      })
      return 'ok'
    } else {
      return Promise.reject(new Error('获取用户信息失败'))
    }
  }
  const clearInfo = async () => {
    const res = await reqLogOut()
    if (res.code == 200) {
      token.value = ''
      Avatar.value = ''
      username.value = ''
      localStorage.removeItem('TOKEN')
      return 'ok'
    } else {
      return Promise.reject(new Error('退出失败'))
    }
  }
  return {
    userLogin,
    token,
    menuRoutes,
    getUserInfo,
    Avatar,
    username,
    clearInfo,
    buttons
  }
})
